package cn.manyufun.myf.ui.user.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;
import cn.manyufun.myf.R;
import cn.manyufun.myf.api.Api;
import cn.manyufun.myf.api.HostType;
import cn.manyufun.myf.app.AppConstant;
import cn.manyufun.myf.bean.LoginBean;
import cn.manyufun.myf.common.base.BaseActivity;
import cn.manyufun.myf.common.baserx.RxSchedulers;
import cn.manyufun.myf.common.baserx.RxSubscriber;
import cn.manyufun.myf.common.commonutils.LogUtils;
import cn.manyufun.myf.common.commonutils.ToastUtil;
import cn.manyufun.myf.common.commonutils.UserInfoUtils;
import cn.manyufun.myf.common.commonwidget.NormalTitleBar;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import static cn.manyufun.myf.common.commonutils.CommonUtils.isTelNumValid;
import static cn.manyufun.myf.common.commonutils.VersionUtils.getVersionCode;

/**
 * A modify screen that offers modify via email/password.
 */
public class LoginAct extends BaseActivity {
    public static final String LOGIN_FROM = "login_from";
    private String mLoginFrom;
    public static void startAction(Context context) {
        Intent intent = new Intent(context, LoginAct.class);
        context.startActivity(intent);
    }

    public static void startAction(Context context, Bundle bundle) {
        Intent intent = new Intent(context, LoginAct.class);
        if (bundle != null)
            intent.putExtras(bundle);

        context.startActivity(intent);
    }

    // UI references.
    @BindView(R.id.et_username)
    EditText mUserNameView;
    @BindView(R.id.password)
    EditText mPasswordView;
    @BindView(R.id.ntb)
    NormalTitleBar ntb;
    @BindView(R.id.sign_in_button)
    Button mBtnSignIn;

    @OnClick(R.id.sign_in_button)
    void login() {
        attemptLogin();
    }

    @OnClick(R.id.tv_register)
    void register() {
        RegisterAcitivty.startAction(this);
    }

    @Override
    public int getLayoutId() {
        return R.layout.act_login;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initView() {
        mLoginFrom = getIntent().getStringExtra(LOGIN_FROM);
        ntb.setTitleText("登录");

        ntb.setOnBackListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });
    }


    /**
     * Attempts to sign in or register the account specified by the modify form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual modify attempt is made.
     */
    private void attemptLogin() {
        // Reset errors.
        mUserNameView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the modify attempt.
        String username = mUserNameView.getText().toString();
        String password = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        if (TextUtils.isEmpty(password) || isPasswordValid(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(username)) {
            mUserNameView.setError(getString(R.string.error_field_required));
            focusView = mUserNameView;
            cancel = true;
        } else if (!isTelNumValid(username)) {
            mUserNameView.setError(getString(R.string.error_invalid_tel));
            focusView = mUserNameView;
            cancel = true;
        }

        if (cancel) {
            focusView.requestFocus();
        } else {
            Api.getDefault(HostType.manyufun).login(getLoginRequestBody(username, password))
                    .compose(RxSchedulers.<LoginBean>io_main())
                    .subscribe(new RxSubscriber<LoginBean>(mContext, false) {
                        @Override
                        public void onStart() {
                            super.onStart();
                            showProgress(true);
                            mBtnSignIn.setClickable(false);
                        }

                        @Override
                        protected void _onNext(LoginBean bean) {
                            showProgress(false);
                            if (bean.getSuccess().equals("1")) {
                                UserInfoUtils.getInstance().modify(bean.getUser());
                                callback();
                                finish();
                            } else {
                                ToastUtil.showLong(bean.getErrorMsg());
                            }
                            mBtnSignIn.setClickable(true);
                        }

                        @Override
                        protected void _onError(String message) {
                            LogUtils.loge(message);
                            showProgress(false);
                            mBtnSignIn.setClickable(true);
                        }
                    });

        }
    }

    private void callback() {
        LogUtils.logd(mLoginFrom);
        if (TextUtils.isEmpty(mLoginFrom))
            return;
        switch (mLoginFrom) {
            case "ComicsDetailActivity":
                mRxManager.post(AppConstant.COMICS_EDIT_COMMENT_OR_ARTICLE, null);
                break;
            case "NewsDetailActivity":
                mRxManager.post(AppConstant.COMICS_EDIT_COMMENT_OR_ARTICLE, null);
                break;

        }
    }

    private RequestBody getLoginRequestBody(String username, String password) {
        JSONObject root = new JSONObject();
        try {
            root.put("AppVersion", getVersionCode(this));
            root.put("DeviceID", "android");
            root.put("UserName", username);
            root.put("Pwd", password);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return RequestBody.create(MediaType.parse("application/json"), root.toString());
    }

    private boolean isPasswordValid(String password) {
        return password.length() < 6;
    }

    private void showProgress(final boolean show) {
        if (show)
            startProgressDialog();
        else
            stopProgressDialog();
    }

}

